/*
 * Array.h
 *
 *  Created on: Aug 13, 2012
 *      Author: nam20485
 *
 *      Simple static-sized array allocated on the heap.
 *      Keeps track of its own length and deletes its memory
 *      when desctructed.
 */

#ifndef ARRAY_H_
#define ARRAY_H_

#include "LinkedList.h"


template <class T>
class Array
{
public:
	Array(T* aElements, unsigned long length)
		: m_aElements(0)
		, m_ulLength(0)
	{
		Populate(aElements, length);
	}

	Array(const LinkedList<T>& list)
		: m_aElements(0)
		, m_ulLength(0)
	{
		if (list.Count() > 0)
		{
			T elements[list.Count()];
			int i = 0;
			typename LinkedList<T>::Node* pNext = list.getHead();
			while (pNext)
			{
				elements[i++] = pNext->Value();
				pNext = pNext->getNext();
			}

			Populate(elements, list.Count());
		}
	}

	virtual ~Array()
	{
		if (m_aElements)
		{
			delete m_aElements;
			m_aElements = 0;
		}
		m_ulLength = 0;
	}

	void Populate(T* aElements, unsigned long length)
	{
		if (length > 0)
		{
			if (aElements)
			{
				m_aElements = (T*) malloc(sizeof(T)*length);
				for (unsigned long l = 0; l < length; l++)
				{
					m_aElements[l] = aElements[l];
				}
			}
			m_ulLength = length;
		}
	}

	//virtual const Array& operator=(const Array& array) {}

	inline T* getElements() const { return m_aElements; }
	inline unsigned long getLength() const { return m_ulLength; }

protected:
	T* m_aElements;
	unsigned long m_ulLength;
};

#endif /* ARRAY_H_ */
